from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from models import lifespan
from middleware.token_middleware import token_validation_middleware
from controllers import (product_service,
                         payment_controller,
                         address,
                         historys,
                         users_service,
                         historys,
                         homepage_carousel,
                         cart_service,
                         hot_product,
                         product_list,
                         sign_in_service,
                         pursh_history)


def create_app() -> FastAPI:
    app = FastAPI(
        title="微格调",
        debug=True,
        version="0.0.1",
        lifespan=lifespan
    )

    return app


app = create_app()


# 注册路由
app.include_router(product_service.router)
app.include_router(payment_controller.router)
app.include_router(address.router)
app.include_router(historys.router)
app.include_router(users_service.router)
app.include_router(homepage_carousel.router)
app.include_router(cart_service.router)
app.include_router(hot_product.router)
app.include_router(product_list.router)
app.include_router(sign_in_service.router)
app.include_router(pursh_history.router)
# 明确指定前端开发环境地址
origins = [
    "http://localhost:5173",
    "http://v8cba8f5.natappfree.cc" # 内网穿透情况用的前端开发地址
]  

# 配置中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*'],
)


# 配置 Token 验证中间件
app.middleware("http")(token_validation_middleware)

